package com.wjm.serversocket.test2;

import com.wjm.serversocket.test1.UploadPicServer;

import java.io.File;
import java.io.RandomAccessFile;


/**
 * 本地文件复制
 * 多线程复制
 * 思路：
 * 每个线程分一部分，如3个线程，每个分1/3
 */
public class MyRunnableCopyFile implements Runnable {

    private int start;
    private int end;

    public MyRunnableCopyFile(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-start-" + start + "-end-" + end);
        try {

//                long startTime; startTime = System.currentTimeMillis();
            copy();

//            System.out.println(Thread.currentThread().getName()+"用时==》"+(System.currentTimeMillis()-startTime)/1000+"s");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void copy() throws Exception {
//        System.out.println(Thread.currentThread().getName() + "-开始复制");
        //输入流
        File file = new File(UploadPicServer.fileStr);
        long length = file.length();

        RandomAccessFile rafIs = new RandomAccessFile(UploadPicServer.fileStr, "r");
        rafIs.seek(start);

        //输出流
        File fileDir = new File(UploadPicServer.pcPf + File.separator + UploadPicServer.serverfilePath);//i:\\server
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File fileOut = new File(fileDir, UploadPicServer.fileName);

        byte[] buf = new byte[20480];
        int len;

        RandomAccessFile rafOut = new RandomAccessFile(fileOut, "rw");
        rafOut.seek(start);
        int lenCount = 0;//用于计算上传进度
        while ((len = rafIs.read(buf)) != -1 && lenCount < end) {
            lenCount += len;
//            System.out.println(Thread.currentThread().getName() + "--len-"+len + "--lenCount-"+lenCount);
            rafOut.write(buf, 0, len);


//            Thread.sleep(1);

        }
        System.out.println(Thread.currentThread().getName() + "-复制完成-lenCount-" + lenCount);

        rafOut.close();

        rafIs.close();

    }
}
